﻿using System;
using System.Threading;

namespace _1115._交替打印FooBar
{
    //https://leetcode.cn/problems/print-foobar-alternately/
    public class FooBar
    {
        private int n;

        public FooBar(int n)
        {
            this.n = n;
        }
        System.Threading.Semaphore sema1 = new System.Threading.Semaphore(0, 1);
        System.Threading.Semaphore sema2 = new System.Threading.Semaphore(1, 1);

        public void Foo(Action printFoo)
        {

            for (int i = 0; i < n; i++)
            {
                sema2.WaitOne();
                // printFoo() outputs "foo". Do not change or remove this line.
                printFoo();
                sema1.Release();
            }
        }

        public void Bar(Action printBar)
        {

            for (int i = 0; i < n; i++)
            {
                sema1.WaitOne();
                // printBar() outputs "bar". Do not change or remove this line.
                printBar();
                sema2.Release();
            }
        }
    }
    class Program
    {
        static FooBar foo = new FooBar(10);

        static void Main(string[] args)
        {

            Thread thread = new Thread(new ParameterizedThreadStart(Foo));
            thread.Name = $"Foo";
            thread.Start(thread.Name);

            Thread thread2 = new Thread(new ParameterizedThreadStart(Bar));
            thread2.Name = $"Bar";
            thread2.Start(thread2.Name);
        }

        static void Foo(object obj)
        {
            foo.Foo(() =>
            {
                Console.WriteLine("Foo");
            });
        }
        static void Bar(object obj)
        {
            foo.Bar(() =>
            {
                Console.WriteLine("Bar");
            });
        }

    }
}
